
//
//  Manager.m
//  Xmpp
//
//  Created by lanou3g on 16/1/28.
//  Copyright © 2016年 徐强. All rights reserved.
//

#import "Manager.h"

typedef NS_ENUM(NSInteger,loginOrRegist){
    login,
    regist
};

static Manager *mg = nil;

@interface Manager()<XMPPStreamDelegate,XMPPRosterDelegate,UIAlertViewDelegate>

@property(nonatomic,assign)loginOrRegist loginOrRegist;

@property(nonatomic,strong)NSString *registPassWord;

@property(nonatomic,strong)NSString *loginPassWord;
//保存
@property (nonatomic,strong )XMPPJID *jid;

//定义有参数无返回值的block，登陆成功后函数回调
@property(nonatomic,copy)void (^loginSuccess)(id data);
@property(nonatomic,copy)void (^loginFail)(id data);
//定义有参数无返回值的block，注册成功后函数回调
@property (nonatomic ,copy)void (^registSuccess)(id data);
@property (nonatomic ,copy)void (^registFail)(id data);
@end


@implementation Manager

//单例方法
+ (instancetype)shareManage{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        mg = [[Manager alloc]init];
        
    });
    
    return mg;
}
//单例方法调用初始化方法
- (instancetype)init{
    self = [super init];
    if (self) {
#warning 创建整个xmpp使用的工具：通讯管道        
        //初始化通讯管道
        self.stream = [[XMPPStream alloc]init];
        //添加代理(代理写在主线程里)
        [self.stream addDelegate:self delegateQueue:dispatch_get_main_queue()];
#warning 创建好友列表
        //初始化好友相关
        //创建数据库
        XMPPRosterCoreDataStorage *storage = [XMPPRosterCoreDataStorage sharedInstance];
        //初始化列表
        self.rost = [[XMPPRoster alloc]initWithRosterStorage:storage dispatchQueue:dispatch_get_main_queue()];
        //添加代理
        [self.rost addDelegate:self delegateQueue:dispatch_get_main_queue()];
        [self.rost activate:self.stream];//激活
        
#warning 聊天消息的保存
        //初始化消息相关的对象
        XMPPMessageArchivingCoreDataStorage *xmppMessageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
        self.archiving = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:xmppMessageStorage dispatchQueue:dispatch_get_main_queue()];
        //激活
        [self.archiving activate:self.stream];
        //获取上下文
        self.context = xmppMessageStorage.mainThreadManagedObjectContext;
    }
    return self;
}

#pragma mark - 注册
- (void)registWithUser:(NSString *)userName passWord:(NSString *)passWord success:(void(^)(id data))success fail:(void(^)(NSError *err))fail
{
    //block 回调，登陆时调用
    self.registSuccess = success;
    self.registFail = fail;
    //全局变量保存密码
    self.registPassWord = passWord;
    //保存当前操作状态
    self.loginOrRegist = regist;
    //注册
    //1.与服务器建立链接
    NSError *error = nil;
    //得到唯一的一个名字 127.0.0.1：默认是自己的域名
    XMPPJID *jid = [XMPPJID jidWithUser:userName domain:@"172.21.62.56" resource:@"iOS"];
    self.stream.myJID = jid;
    //应用的端口号XMPP默认端口号
    self.stream.hostPort = 5222;
    //对应自己的域名IP地址
    self.stream.hostName = @"172.21.62.56";
    //若正在登陆／已经登陆，断开链接
    if ([self.stream isConnecting] || [self.stream isConnected]) {
        [self.stream disconnect];
    }
    [self.stream connectWithTimeout:20 error:&error];
    //2.链接成功后发送密码
    //3.代理中接收注册的结果
}
#pragma mark - delegate
//与服务器链接成功会调用的方法
- (void)xmppStreamDidConnect:(XMPPStream *)sender{
    
    //根据操作状态，发送对应的密码
    switch (self.loginOrRegist) {
        case regist:
            //2.发送注册密码
            [self.stream registerWithPassword:self.registPassWord error:nil];
            break;
            
        case login:
            //2.发送登陆密码
            [self.stream authenticateWithPassword:self.loginPassWord error:nil];
            break;
    }
}
//断开链接
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
}
//与服务器链接失败会调用的方法
-(void)xmppStreamConnectDidTimeout:(XMPPStream *)sender{
}
//3.代理中接收注册的结果
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
    NSLog(@"成功注册");
    self.registSuccess(@"1");
}
//注册失败
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error{
    NSLog(@"注册失败");
    self.registFail(@"1");
}

#pragma mark - 登陆
- (void)loginWithUser:(NSString *)userName passWord:(NSString *)passWord success:(void(^)(id data))success fail:(void(^)(NSError *err))fail
{
    //block 回调，登陆时回调
    self.loginSuccess = success;
    self.loginFail = fail;
    //保存登陆密码
    self.loginPassWord = passWord;
    self.loginOrRegist = login;
    //1.与服务器建立链接
    NSError *error = nil;
    XMPPJID *jid = [XMPPJID jidWithUser:userName domain:@"lanou3gdemac-mini.local" resource:@"iOS"];
    self.stream.myJID = jid;
    self.stream.hostPort = 5222;       //默认
    self.stream.hostName = @"172.21.62.56";   //ip地址
    //若正在登陆／已经登陆，断开链接
    if ([self.stream isConnecting] || [self.stream isConnected]) {
        [self.stream disconnect];
    }
    [self.stream connectWithTimeout:20 error:&error];
    //2.发送密码
    //3.登录结果
    //发送在线消息
}
//登陆成功
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    NSLog(@"登陆成功");
    //发送在线消息:点亮头像
    XMPPPresence *pre = [XMPPPresence presence];
    //另一种发送在线的消息
//    XMPPPresence *prec = [XMPPPresence presenceWithType:@"available"];
    [self.stream sendElement:pre];
    
    //防止被提前释放
    if (self.loginSuccess) {
        //block回调，执行跳转页面的功能
        self.loginSuccess(@"1");
    }else{
        self.loginFail(@"1");
    }
}
//登陆失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    NSLog(@"%@",error);
    NSLog(@"登陆失败");
    self.loginFail(@"1");
}
#pragma mark - 注销
//注销
- (void)loginOut
{
    //0.发送下线通知
    XMPPPresence *pre = [XMPPPresence presenceWithType:@"unavailable"];
    [self.stream sendElement:pre];
    //1.断开链接
    [self.stream disconnect];
}

#pragma mark - XMPPRosterDelegate
//获取到好友请求
- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence{
    
    
    self.jid = presence.from;
    
    UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@想添加你为好友",self.jid.user] delegate:self cancelButtonTitle:@"拒绝" otherButtonTitles:@"添加", nil];
    
    [view show];
 
}

#pragma mark -UIAlertViewDelegate方法
//点击哪个按钮对应操作
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:{
            //拒绝
            [self.rost rejectPresenceSubscriptionRequestFrom:self.jid];
            break;
        }
        case 1:{
            //同意
            [self.rost acceptPresenceSubscriptionRequestFrom:self.jid andAddToRoster:YES];
            break;
        }
        default:
            break;
    }
}
//添加好友
- (void)addFriendWith:(XMPPJID *)pjid
{
    //监听好友状态
    [self.rost subscribePresenceToUser:pjid];
    //添加好友
    [self.rost addUser:pjid withNickname:pjid.user];
}
//删除好友
- (void)removeFriendWith:(XMPPJID *)pjid
{
    //取消好友的监听状态
    [self.rost unsubscribePresenceFromUser:pjid];
    //移除好友
    [self.rost removeUser:pjid];
}

@end
